package xmysql

import (
	"database/sql"
	"time"

	"gitee.com/githubdog/goci/tools/helper"
)

// CheckConn 验证连接是否有效
func (db *DbTCP) checkConn(dbConf DBConf) bool {
	return db.ConnUUID != "" && db.ConnUUID == helper.Md5String(getDsnByConf(dbConf, protocolTCP))
}

// Conn ..
func (db *DbTCP) Conn(dbConf DBConf) (err error) {
	db.Conf = dbConf
	db.DSN = getDsnByConf(dbConf, protocolTCP)

	if db.DbClient, err = sql.Open("mysql", db.DSN); err == nil {
		db.DbClient.SetConnMaxLifetime(time.Hour * 2)
		if dbConf.MaxOpenConns > 0 {
			db.DbClient.SetMaxOpenConns(dbConf.MaxOpenConns)
			db.DbClient.SetMaxIdleConns(dbConf.MaxIdleConns)
			if dbConf.ConnMaxLifetime > 0 {
				db.DbClient.SetConnMaxLifetime(time.Second * time.Duration(dbConf.ConnMaxLifetime))
			}
		}
		db.ConnUUID = helper.Md5String(db.DSN)
	}
	return err
}

// Close ..
func (db *DbTCP) Close() {
	if db.DbClient != nil {
		db.DbClient.Close()
	}
}

func (db *DbTCP) DbQueryTest() error {
	return db.DbClient.QueryRow("SELECT version();").Scan(&db.Version)
}
